package com.lis.scf.service.impl;

import com.lis.scf.common.dto.CurrentUserDTO;
import com.lis.scf.common.enums.BusinessExceptionEnum;
import com.lis.scf.entity.Company;
import com.lis.scf.entity.User;
import com.lis.scf.exception.BusinessException;
import com.lis.scf.repository.CompanyRepository;
import com.lis.scf.repository.UserRepository;
import com.lis.scf.service.UserService;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final CompanyRepository companyRepository;

    /**
     * 获取当前登录用户信息（含企业信息）
     */
    @Override
    @Transactional(readOnly = true) // 只读事务，优化查询
    public CurrentUserDTO getCurrentUserInfo(String username) {
        // 1. 查询用户信息
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException(BusinessExceptionEnum.USER_NOT_FOUND));

        Company company = user.getCompany();




        // 2. 查询所属企业信息
//        Company company = companyRepository.findById(user.getCompany().getCompanyId())
//                .orElseThrow(() -> new BusinessException(BusinessExceptionEnum.COMPANY_NOT_FOUND));

        // 3. 转换为DTO并返回
        CurrentUserDTO dto = new CurrentUserDTO();
        // 设置用户信息
        dto.setUserId(user.getUserId());
        dto.setUsername(user.getUsername());
        dto.setRealName(user.getRealName());
        dto.setMobileNumber(user.getMobileNumber());
        dto.setIsActive(user.getIsActive());
        // 格式化时间（如果不为空）
        if (user.getLastLoginTime() != null) {
            dto.setLastLoginTime(user.getLastLoginTime()
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        // 设置企业信息
        dto.setCompanyId(company.getCompanyId());
        dto.setCompanyName(company.getCompanyName());
        dto.setCompanyType(company.getCompanyType());
        dto.setUnifiedCreditCode(company.getUnifiedCreditCode());

        return dto;
    }

    // 其他用户相关方法实现...
}
